/****************************************************************/
var tree, treeNodes;
/****************************************************************/
function loadTreeObj(terNodes, selCatId){
	//需要具体用到地方重写此方法
}
function initTree(nodes, isOpenAll, selCatId){
	//需要具体用到地方重写此方法
}
Array.prototype._distinct=function(){//数组元素去重方法
	var newArr=[],obj={}; 
	for(var i=0,len=this.length;i<len;i++){
		if(!obj[typeof(this[i])+this[i]]){
			newArr.push(this[i]); 
			obj[typeof(this[i])+this[i]]='new'; 
		}
	}
	return newArr; 
};

var preKeyword,_isFirst = true;
function filtTerTree(v){
	var keyword = v.toUpperCase().replace(/\s+/g,'');
	if(_isFirst){
		preKeyword = keyword;
	}
	var resultArr = [];
	var indexArr = [];
	var parentIdArr = [];
	if(preKeyword!=keyword || _isFirst){
		_isFirst = false;
		var isOpenAll = true;
		if(!!keyword && keyword.length > 0){
			var _pyKeyword = PYUtil.makePy(keyword).join(),_pyNodeText;
			for(var i=0; i<treeNodes.length; i++){
				 _pyNodeText = PYUtil.makePy(treeNodes[i].name).join();
				if(treeNodes[i].leafLev == '1' && (treeNodes[i].name.toUpperCase().indexOf(keyword)!=-1 || _pyNodeText.indexOf(_pyKeyword)!=-1)){
					indexArr.push(i);
					parentIdArr.push(treeNodes[i].pId);
				}
			}
			if(indexArr.length > 0){
				parentIdArr = parentIdArr._distinct();
				chooseNode(indexArr,parentIdArr);
			}

			indexArr = indexArr._distinct();
			resultArr = getJSONArray(indexArr);
		}else{
			resultArr = treeNodes;
			isOpenAll = false;
		}
		
		$.fn.zTree.destroy("tree");//先销毁已有的树对象
		initTree(resultArr, true);//初始化终端树
		preKeyword = keyword.replace(/\s+/g,'');
	}
}

function chooseNode(indexArr,parentIdArr){
	var _parentIdArr = [];
	for(var j=0; j<parentIdArr.length; j++){
		for(var i=0; i<treeNodes.length; i++){
			if(treeNodes[i].id == parentIdArr[j]){
				indexArr.push(i);
				_parentIdArr.push(treeNodes[i].pId);
			}
		}
	}
	if(_parentIdArr.length > 0){
		_parentIdArr = _parentIdArr._distinct();
		chooseNode(indexArr,_parentIdArr);
	}
}
function getJSONArray(indexArr){
	var arry = [],index;
	for(var i=0; i<indexArr.length; i++){
		index = indexArr[i];
		arry.push(treeNodes[index]);
	}
	return arry;
}
